<template>
  <div class="blockchain-status">
    <!-- 区块链连接状态 -->
    <el-card class="status-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <el-icon><Link /></el-icon>
          <span>区块链状态</span>
          <el-button 
            v-if="!isConnected && isWeb3Available"
            type="primary" 
            size="small"
            @click="connectWallet"
            :loading="loading"
          >
            连接钱包
          </el-button>
          <el-button 
            v-else-if="isConnected"
            type="danger" 
            size="small"
            @click="disconnectWallet"
          >
            断开连接
          </el-button>
        </div>
      </template>

      <div class="status-content">
        <!-- Web3 不可用 -->
        <div v-if="!isWeb3Available" class="status-item">
          <el-alert
            title="Web3 钱包未检测到"
            type="warning"
            description="请安装 MetaMask 或其他兼容的 Web3 钱包以使用区块链功能"
            :closable="false"
          />
        </div>

        <!-- 已连接状态 -->
        <div v-else-if="isConnected" class="connected-status">
          <div class="status-item">
            <label>钱包地址：</label>
            <el-input
              :value="formatAddress(account)"
              readonly
              size="small"
            >
              <template #append>
                <el-button @click="copyAddress">
                  <el-icon><CopyDocument /></el-icon>
                </el-button>
              </template>
            </el-input>
          </div>

          <div class="status-item">
            <label>网络：</label>
            <el-tag :type="getNetworkType()">{{ networkName }}</el-tag>
          </div>

          <div class="status-item" v-if="balance !== null">
            <label>余额：</label>
            <span class="balance">{{ balance }} ETH</span>
          </div>
        </div>

        <!-- 未连接状态 -->
        <div v-else class="disconnected-status">
          <el-empty 
            description="钱包未连接"
            :image-size="80"
          >
            <el-button type="primary" @click="connectWallet" :loading="loading">
              连接钱包
            </el-button>
          </el-empty>
        </div>

        <!-- 错误信息 -->
        <el-alert
          v-if="error"
          :title="error"
          type="error"
          :closable="true"
          @close="clearError"
          class="error-alert"
        />
      </div>
    </el-card>

    <!-- 区块链功能开关 -->
    <el-card class="feature-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <el-icon><Setting /></el-icon>
          <span>区块链功能</span>
        </div>
      </template>

      <div class="feature-content">
        <el-switch
          v-model="blockchainEnabled"
          active-text="启用区块链"
          inactive-text="仅数据库模式"
          :disabled="!isConnected"
          @change="handleBlockchainToggle"
        />
        
        <div class="feature-description">
          <p v-if="blockchainEnabled && isConnected">
            <el-icon><Check /></el-icon>
            区块链功能已启用，所有操作将同步到区块链
          </p>
          <p v-else-if="!isConnected">
            <el-icon><Warning /></el-icon>
            请先连接钱包以启用区块链功能
          </p>
          <p v-else>
            <el-icon><InfoFilled /></el-icon>
            当前仅使用数据库存储，不会同步到区块链
          </p>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useBlockchainStore } from '@/stores/blockchain'
import { ElMessage } from 'element-plus'
import {
  Link,
  CopyDocument,
  Setting,
  Check,
  Warning,
  InfoFilled
} from '@element-plus/icons-vue'

const blockchainStore = useBlockchainStore()

// 状态
const balance = ref(null)
const blockchainEnabled = ref(false)

// 计算属性
const isConnected = computed(() => blockchainStore.isConnected)
const isWeb3Available = computed(() => blockchainStore.isWeb3Available)
const account = computed(() => blockchainStore.account)
const networkName = computed(() => blockchainStore.networkName)
const loading = computed(() => blockchainStore.loading)
const error = computed(() => blockchainStore.error)

// 方法
const connectWallet = async () => {
  const result = await blockchainStore.connectWallet()
  if (result.success) {
    ElMessage.success('钱包连接成功')
    await loadBalance()
    blockchainEnabled.value = true
  } else {
    ElMessage.error(result.message)
  }
}

const disconnectWallet = () => {
  blockchainStore.disconnectWallet()
  balance.value = null
  blockchainEnabled.value = false
  ElMessage.info('钱包已断开连接')
}

const loadBalance = async () => {
  try {
    balance.value = await blockchainStore.getBalance()
  } catch (err) {
    console.error('获取余额失败:', err)
  }
}

const formatAddress = (address) => {
  if (!address) return ''
  return `${address.slice(0, 6)}...${address.slice(-4)}`
}

const copyAddress = async () => {
  try {
    await navigator.clipboard.writeText(account.value)
    ElMessage.success('地址已复制到剪贴板')
  } catch (err) {
    ElMessage.error('复制失败')
  }
}

const getNetworkType = () => {
  if (!networkName.value) return 'info'
  
  if (networkName.value.includes('Mainnet')) return 'success'
  if (networkName.value.includes('Testnet')) return 'warning'
  if (networkName.value.includes('Local')) return 'danger'
  
  return 'info'
}

const clearError = () => {
  blockchainStore.error = ''
}

const handleBlockchainToggle = (enabled) => {
  if (enabled && !isConnected.value) {
    ElMessage.warning('请先连接钱包')
    blockchainEnabled.value = false
    return
  }
  
  ElMessage.success(
    enabled ? '区块链功能已启用' : '已切换到仅数据库模式'
  )
}

// 初始化
onMounted(async () => {
  // 检查是否已经连接
  const connected = await blockchainStore.checkConnection()
  if (connected) {
    await loadBalance()
    blockchainEnabled.value = true
  }
})
</script>

<style scoped>
.blockchain-status {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
}

.card-header .el-button {
  margin-left: auto;
}

.status-content {
  min-height: 120px;
}

.connected-status {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.status-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-item label {
  font-weight: 500;
  color: #606266;
  min-width: 80px;
  flex-shrink: 0;
}

.balance {
  font-weight: 500;
  color: #67c23a;
}

.disconnected-status {
  padding: 20px 0;
}

.error-alert {
  margin-top: 12px;
}

.feature-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.feature-description {
  padding-top: 8px;
}

.feature-description p {
  display: flex;
  align-items: center;
  gap: 6px;
  margin: 0;
  font-size: 13px;
  color: #606266;
}

.feature-description .el-icon {
  font-size: 14px;
}

/* 响应式 */
@media (max-width: 768px) {
  .status-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
  
  .status-item label {
    min-width: auto;
  }
}
</style>